﻿using Coldairarrow.Business.Base_Manage;
using Coldairarrow.Entity.Base_leasesystem_accountrecharge;
using Coldairarrow.Entity.Base_leasesystem_bankcard;
using Coldairarrow.Entity.Base_leasesystem_billingaddress;
using Coldairarrow.Entity.Base_leasesystem_invoiceinformation;
using Coldairarrow.Entity.Base_leasesystem_merchant;
using Coldairarrow.Entity.Base_leasesystem_merchant_img;
using Coldairarrow.Entity.Base_leasesystem_merchantpaychannel;
using Coldairarrow.Entity.Base_leasesystem_transactionbatch;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Entity.ViewModel;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_leasesystem_merchant
{
    public class leasesystem_merchantBusiness : BaseBusiness<leasesystem_merchant>, Ileasesystem_merchantBusiness, ITransientDependency
    {
        public leasesystem_merchantBusiness(IDbAccessor db, IHomeBusiness homeBusiness)
            : base(db)
        {
            _homebusiness = homeBusiness;
        }
        IHomeBusiness _homebusiness { get; set; }
        #region 外部接口

        public async Task<PageResult<leasesystem_merchant>> GetDataListAsync(PageInput<ConditionDTO> input,string userid)
        {
            var q = GetIQueryable();
            var where = LinqHelper.True<leasesystem_merchant>();
            var search = input.Search;

            //筛选
            if (!search.Condition.IsNullOrEmpty() && !search.Keyword.IsNullOrEmpty())
            {
                var newWhere = DynamicExpressionParser.ParseLambda<leasesystem_merchant, bool>(
                    ParsingConfig.Default, false, $@"{search.Condition}.Contains(@0)", search.Keyword);
                where = where.And(newWhere);
            }

            return await q.Where(where).GetPageResultAsync(input);
        }

        public async Task<leasesystem_merchant> GetTheDataAsync(string id)
        {
            return await GetEntityAsync(id);
        }

        public async Task AddDataAsync(leasesystem_merchant data)
        {
           
            await InsertAsync(data);

        }

        public async Task AddMer_bank_invoiceinfo(MerchantAll merchantAll)
        {
            #region  新增银行信息
            leasesystem_bankcard bankcard = new leasesystem_bankcard();
            bankcard.AccountBank = merchantAll.AccountBank;
            bankcard.AccountName = merchantAll.AccountName;
            bankcard.BankNo = merchantAll.BankNo;
            bankcard.MID = merchantAll.Id;
            bankcard.Id = IdHelper.GetId();
            bankcard.CreateTime = merchantAll.CreateTime;
            bankcard.CreatorId = merchantAll.CreatorId;
            await Db.InsertAsync(bankcard);
            #endregion

            #region  新增开票信息
            leasesystem_invoiceinformation invoice = new leasesystem_invoiceinformation();
            invoice.MID = merchantAll.Id;
            invoice.Id = IdHelper.GetId();
            invoice.CreateTime = merchantAll.CreateTime;
            invoice.CreatorId = merchantAll.CreatorId;
            invoice.DepositBank = merchantAll.AccountBank;
            invoice.InvoiceRise = merchantAll.customerName;
            invoice.TaxRegistrationNo = merchantAll.customTaxIdcd;
            invoice.RegisteredTelephone = merchantAll.customCollectorPhone;
            invoice.RegisteredAddr = merchantAll.areaName;
            invoice.BankAccount = merchantAll.BankNo;
            await Db.InsertAsync(invoice);

            #endregion

            #region  新增发票地址信息
            leasesystem_billingaddress bill = new leasesystem_billingaddress();
            bill.Id = IdHelper.GetId();
            bill.CreateTime = merchantAll.CreateTime;
            bill.CreatorId = merchantAll.CreatorId;
            bill.MID = merchantAll.Id;
            bill.RecipientName = merchantAll.customerName;
            bill.Phone = merchantAll.customCollectorPhone;
            bill.RecipientAddr = merchantAll.areaName;
            bill.IsDefault = 1;
            await Db.InsertAsync(bill);
            #endregion
            await InsertAsync(merchantAll);
            
        }

        public async Task UpdateDataAsync(leasesystem_merchant data)
        {
            if (data.CheckStatus ==1) {
                Base_User user = new Base_User();
                user.Id = IdHelper.GetId();
                user.CreateTime = data.CreateTime;
                user.CreatorId = data.CreatorId;
                user.Deleted = false;
                user.UserName = data.customerTelephone;
                user.Password = "666888".ToMD5String();
                user.RealName = data.customerName;
                user.Sex = Sex.Man;
                user.email = data.customMail;
                user.telephone = data.customerTelephone;
                user.brandId = data.Id;
                user.brandName = data.customerName;
                await Db.InsertAsync(user);


                Base_UserRole ur = new Base_UserRole();
                ur.Id = IdHelper.GetId();
                ur.CreateTime = data.CreateTime;
                ur.CreatorId = data.CreatorId;
                ur.Deleted = false;
                ur.UserId = user.Id;
                ur.RoleId = "1514160327997001728";
            }
            await UpdateAsync(data);
        }

        public async Task DeleteDataAsync(List<string> ids)
        {
            List<leasesystem_merchant> list = new List<leasesystem_merchant>();
            for (int i = 0; i < ids.Count; i++)
            {
              list.Add(GetEntity(ids[i]));
            }

            list.ForEach(a => a.CheckStatus = 3);

            list.ForEach(a=> {
                if (!a.FrontofIDCard.IsNullOrEmpty()) {
                    string FrontofIDCard = a.FrontofIDCard.Split('/')[4];
                     _homebusiness.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{FrontofIDCard}");
                    
                }
                if (!a.ReversesideofIDCard.IsNullOrEmpty())
                {
                    string ReversesideofIDCard = a.ReversesideofIDCard.Split('/')[4];
                    _homebusiness.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{ReversesideofIDCard}");
             
                }
                if (!a.Businesslicense.IsNullOrEmpty())
                {
                    string Businesslicense = a.Businesslicense.Split('/')[4];
                    _homebusiness.DeleteFile(Directory.GetCurrentDirectory() + $"\\wwwroot\\Upload\\{Businesslicense}");
                }
            });
            await UpdateAsync(list);

            //await DeleteAsync(ids);
        }

        /// <summary>
        /// 连表查询   客户及客户银行
        /// </summary>
        /// <returns></returns>
        public object GetListAll(string input) {
            var list = from chant in Db.GetIQueryable<leasesystem_merchant>()
                       join mer_img in Db.GetIQueryable<leasesystem_bankcard>()
                       on chant.Id equals mer_img.MID into temp
                       from tempT in temp.DefaultIfEmpty()
                       where chant.Id == input
                       select new {
                           Id = chant.Id,
                           customerName = chant.customerName,
                           customTaxIdcd = chant.customTaxIdcd,
                           customLegalPerson = chant.customLegalPerson,
                           IdNumber = chant.IdNumber,
                           customCollector = chant.customCollector,
                           customCollectorPhone = chant.customCollectorPhone,
                           customMail = chant.customMail,
                           customerTelephone = chant.customerTelephone,
                           areaName = chant.areaName,
                           AgentId = chant.AgentId,
                           customerManager = chant.customerManager,
                           createTime = chant.CreateTime,
                           creatorId = chant.CreatorId,
                           CheckStatus = chant.CheckStatus,
                           FrontofIDCard = chant.FrontofIDCard,
                           ReversesideofIDCard = chant.ReversesideofIDCard,
                           chant.customerManagerId,
                           Businesslicense = chant.Businesslicense,
                           AccountBank = tempT.AccountBank,
                           BankNo = tempT.BankNo,
                           BankId = tempT.Id,
                           tempT.AccountName,
                       };
            return list;
        }

        //客户表  下拉框
        public List<SelectModel> FullSelect()
        {
            
                List<SelectModel> list = new List<SelectModel>();
                var a = Db.GetIQueryable<leasesystem_merchant>().Select(a => new {
                    value = a.Id,
                    text = a.customerName
                }).ToList();

                foreach (var item in a)
                {
                    SelectModel s = new SelectModel();
                    s.value = item.value;
                    s.text = item.text;
                    list.Add(s);
                }

                return list;
            
        }

        /// <summary>
        /// 查询客户表   及  代发通道表
        /// </summary>
        /// <returns>客户信息及客户代发通道数量</returns>
        public object GetCustomCheck()
        {
            var list = from chant in Db.GetIQueryable<leasesystem_merchant>()
                       join mer_img in Db.GetIQueryable<leasesystem_merchantpaychannel>()
                       on chant.Id equals mer_img.MID into temp
                       from tempT in temp.DefaultIfEmpty()
                       select new
                       {
                           Id = chant.Id,
                           createTime = chant.CreateTime,
                           creatorId = chant.CreatorId,
                           PaychanneNum = Db.GetEntity<leasesystem_merchantpaychannel>(chant.Id)
                       };
            return list;
        }

        public object GetHeightSearch(PageInput<ConditionDTO> input)
        {
            var q = Db.GetIQueryable<leasesystem_merchant>().Where(a=>a.CheckStatus != 3);
            var newWhere = q;


            if (!input.Search.Keyword.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.customerName.Contains(input.Search.Keyword));
            }
            if (!input.Search.customTaxIdcd.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.customTaxIdcd.Contains(input.Search.customTaxIdcd));
            }

            if (!input.Search.customLegalPerson.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.customLegalPerson.Contains(input.Search.customLegalPerson));
            }
            if (!input.Search.IdNumber.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.IdNumber.Contains( input.Search.IdNumber));
            }
            if (!input.Search.customCollector.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.customCollector.Contains(input.Search.customCollector));
            }
            if (!input.Search.customCollectorPhone.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.customCollectorPhone.Contains(input.Search.customCollectorPhone));
            }
            if (!input.Search.Status.IsNullOrEmpty())
            {
                newWhere = newWhere.Where(a => a.CheckStatus.ToString() == input.Search.Status);
            }


            var Data = new
            {
                Data = newWhere.Skip((input.PageIndex - 1) * input.PageRows)
               .Take(input.PageRows),
                Total = q.Count()
            };
            return Data;

        }

        public async Task EditMer_bank_invoiceinfo(MerchantAll merchant)
        {
            if (merchant.CheckStatus == 1)
            {
                var userinfo = Db.GetIQueryable<Base_User>().Where(a => a.brandId == merchant.Id);
                if (userinfo.Count()<1) {
                    Base_User user = new Base_User();
                    user.Id = IdHelper.GetId();
                    user.CreateTime = merchant.CreateTime;
                    user.CreatorId = merchant.CreatorId;
                    user.Deleted = false;
                    user.UserName = merchant.customerTelephone;
                    user.Password = "666888".ToMD5String();
                    user.RealName = merchant.customerName;
                    user.Sex = Sex.Man;
                    user.email = merchant.customMail;
                    user.telephone = merchant.customerTelephone;
                    user.brandId = merchant.Id;
                    user.brandName = merchant.customerName;
                    await Db.InsertAsync(user);

                    Base_UserRole ur = new Base_UserRole();
                    ur.Id = IdHelper.GetId();
                    ur.CreateTime = merchant.CreateTime;
                    ur.CreatorId = merchant.CreatorId;
                    ur.Deleted = false;
                    ur.UserId = user.Id;
                    ur.RoleId = "1514160327997001728";
                    await Db.InsertAsync(ur);
                }
                
            }
            var merchantinfo =await Db.GetEntityAsync<leasesystem_merchant>(merchant.Id);
            //修改客户信息
            await UpdateAsync(merchant);

            //修改银行信息
            var bank =await Db.GetEntityAsync<leasesystem_bankcard>(merchant.BankId);
            bank.AccountBank = merchant.AccountBank;
            bank.AccountName = merchant.AccountName;
            bank.BankNo = merchant.BankNo;
            await Db.UpdateAsync(bank);

            //修改开票信息
            var invoiceinfo =await Db.GetIQueryable<leasesystem_invoiceinformation>().Where(a => a.MID == merchant.Id).FirstOrDefaultAsync();
            invoiceinfo.InvoiceRise = merchant.customerName;
            invoiceinfo.TaxRegistrationNo = merchant.customTaxIdcd;
            invoiceinfo.RegisteredTelephone = merchant.customerTelephone;
            invoiceinfo.RegisteredAddr = merchant.areaName;
            invoiceinfo.DepositBank = merchant.AccountBank;
            invoiceinfo.BankAccount = merchant.BankNo;
            await Db.UpdateAsync(invoiceinfo);

            //充值信息中的客户名称
            //if (merchant.customerName != merchantinfo.customerName) {
            //    var recharge = Db.GetIQueryable<leasesystem_accountrecharge>().Where(a => a.MID == merchant.Id);
            //    await recharge.ForEachAsync(a => a.customerName = merchant.customerName);
            //}

        }

        #endregion

        #region 私有成员

        #endregion
    }
}